package com.mwj.auction.controller;


import com.mwj.auction.utils.FileUtil;
import com.mwj.auction.utils.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.UUID;

import static com.mwj.auction.utils.FileUtil.compressionVideo;

@RequestMapping("/upload")
@CrossOrigin("*")
@RestController
public class uploadFileController {
    /**
     * 上传图片
     */
    @PostMapping("/uploadFile")
    public Result upload(@RequestParam("file") MultipartFile file){
        return uploadFile(file);
    }


    /**
     * 上传文件
     */
    public Result uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }
        long size = file.getSize();
//        String ip = "../../static/TestImg/"; // 根据需要配置IP
        String ip = "http://103.56.112.53:7777/";


        try {
            String originalFileName = file.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + fileExtension;

            // String uploadDir = "F:/cf/imgTest/"; // Windows 测试地址
//            String uploadDir = "/Applications/我的项目盘（A）/TestImg/ "; // mac测试地址

//             String uploadDir = "/www/wwwroot/h5/img/";

            String uploadDir = "/C:/wwwroot/h5/img/";

//             String uploadDir = "/Applications/我的项目盘（A）/2024/小马密聊/XmChat/static/TestImg/";


            String filePath = uploadDir + newFileName;

            // 使用InputStream直接处理上传文件
            try (InputStream inputStream = file.getInputStream();
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

                if (fileExtension.equalsIgnoreCase(".jpg") ||
                        fileExtension.equalsIgnoreCase(".jpeg") ||
                        fileExtension.equalsIgnoreCase(".png")) {
                    // 压缩图片
                    FileUtil.compressImage(inputStream, outputStream, 0.4f); // 0.4 为压缩质量
                    // 保存压缩后的图片到指定路径
                    try (FileOutputStream fos = new FileOutputStream(filePath)) {
                        size = outputStream.size();
                        fos.write(outputStream.toByteArray());
                    }
                } else if (fileExtension.equalsIgnoreCase(".mp4") ||
                        fileExtension.equalsIgnoreCase(".avi") ||
                        fileExtension.equalsIgnoreCase(".mkv")) {
                    // 处理视频压缩
                    File tempFile = File.createTempFile("video_", fileExtension);
                    file.transferTo(tempFile); // 临时保存视频文件

                    File compressedFile = compressionVideo(tempFile, newFileName);
                    size = compressedFile.length();

                    // 将压缩后的文件移动到目标目录
                    File dest = new File(filePath);
                    if (!compressedFile.renameTo(dest)) {
                        throw new IOException("压缩后的视频文件移动失败");
                    }
                }  else {
                    // 其他文件直接保存
                    File dest = new File(filePath);
                    file.transferTo(dest);
                }
            }

            String formatFileSize = formatFileSize(size);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("url", ip + newFileName);
            map.put("size", formatFileSize);
            return Result.success("上传成功", map);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(201, "上传失败");
        }
    }


    /**
     * 格式化文件大小
     * @param size
     * @return
     */
    public String formatFileSize(long size) {
        if (size < 1024) {
            return size + " B";
        } else if (size < 1024 * 1024) {
            return String.format("%.2f KB", size / 1024.0);
        } else {
            return String.format("%.2f MB", size / (1024.0 * 1024.0));
        }
    }
}
